package com.bootlever.framework.rmi.templates;

import com.bootlever.framework.common.utils.StringUtils;
import com.bootlever.framework.rmi.annotation.RmiServer;
import com.bootlever.framework.rmi.bean.BootleverRmiContainer;
import com.bootlever.framework.rmi.bean.RmiClient;
import com.bootlever.framework.rmi.bean.RmiInfo;
import com.bootlever.framework.rmi.constant.RmiClientBalanced;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.rmi.Naming;
import java.util.List;
import java.util.Random;

@Component
public class RmiTemplate {

    private static final Logger logger = LoggerFactory.getLogger(RmiTemplate.class);

    private static final Random random = new Random(100);

    @Autowired
    private BootleverRmiContainer container;

    public RmiTemplate(){}


    public BootleverRmiContainer getContainer() {
        return container;
    }

    public void setContainer(BootleverRmiContainer container) {
        this.container = container;
    }

    public Object get(Class<?> clazz){
        return get(clazz, RmiClientBalanced.RANDON,false);
    }

    public Object get(Class<?> clazz, RmiClientBalanced rmiClientBalanced, boolean onlyOkStatus){
        RmiInfo target = null;
        if (rmiClientBalanced == null) {
            rmiClientBalanced = RmiClientBalanced.RANDON;
        }
        RmiServer rmiServerAnnotation = clazz.getAnnotation(RmiServer.class);
        if (rmiServerAnnotation==null){
            return null;
        }
        String appName = rmiServerAnnotation.appName();
        String name = clazz.getSimpleName();
        if (StringUtils.isNotBlank(rmiServerAnnotation.name())){
            name = rmiServerAnnotation.name();
        }
        RmiClient rmiClient = container.getClient(appName);
        if (rmiClient == null) {
            return null;
        }
        List<RmiInfo> rmiInfos = rmiClient.getOkStatusInfos().get(name);
        if (rmiInfos == null || rmiInfos.isEmpty()) {
            if (onlyOkStatus == true){
                return null;
            } else {
                rmiInfos = rmiClient.getBusyStatusInfos().get(name);
            }
        }
        if (rmiInfos == null || rmiInfos.isEmpty()) {
            return null;
        }
        if (RmiClientBalanced.RANDON == rmiClientBalanced) {
            target =  rmiInfos.get(random.nextInt()%rmiInfos.size());
        }
        if (target == null) {
            return null;
        }
        String address = target.getAddress();
        try {
            return Naming.lookup(address);
        } catch (Exception e) {
            logger.error("获取RmiClient失败",e);
            return null;
        }
    }


}
